#!/usr/bin/env python

import socket
import sys

server_addr = ("127.0.0.1", 8080)
calc_addr = ("127.0.0.1", int(sys.argv[1]))
recv_len = 1024
calc_count = 3
n = int(1e4)

def func(x):
    return x
def integral(a, b):
    dx = (b - a) / n
    x = a
    res = 0
    for i in range(n):
        res += dx * func(x)
        x += dx
    return res

#Bind socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(calc_addr)
print("Start calculator")

while True:
#Recv argc from Server
    a, server_addr = sock.recvfrom(recv_len)
    b, server_addr = sock.recvfrom(recv_len)
    a, b = float(a.decode()), float(b.decode())
    if a > b:
        a, b = b, a
    print(a, " | ", b)

#Send result to Server
    while True:
        msg, server_addr = sock.recvfrom(recv_len)
        if msg.decode() == "READY":
            break
    sock.sendto(str(integral(a, b)).encode(), server_addr)
